//UI初始化
layui.use(['element', 'layer', 'form', 'table'], function () {
    var form = layui.form;
    var layer = layui.layer;
    var colActEditor = new ComponetEditor("#btnShowView", "#btnView", "#btnEdit",false);
    var colEditor = new ComponetEditor("#colShowView", "#colView", "#colEdit",false);
    var actEditor = new ComponetEditor("#queryActView", "#btnView", "#btnEdit",false);
    var condEditor = new ComponetEditor("#queryConView", "#fieldView", "#fieldEdit",true);
    var formActEditor = new ComponetEditor("#formActView", "#btnView", "#btnEdit",false);
    var formColEditor = new ComponetEditor("#formColView", "#fieldView", "#fieldEdit",true);
    var viewColEditor = new ComponetEditor("#viewColView", "#viewView", "#viewEdit",true);

    //自定义验证规则
    form.verify(verify_rule);
    //监听提交
    form.on('submit(save)', function (data) {
        data.field.queryColActJson = JSON.stringify(colActEditor.getData());
        data.field.queryColJson = JSON.stringify(colEditor.getData());
        data.field.queryActJson = JSON.stringify(actEditor.getData());
        data.field.queryConJson = JSON.stringify(condEditor.getData());
        data.field.formActJson = JSON.stringify(formActEditor.getData());
        data.field.formColJson = JSON.stringify(formColEditor.getData());
        data.field.viewColJson = JSON.stringify(viewColEditor.getData());
        $.ajax({
            url: "/page/save",
            dataType: "json",
            method: "POST",
            data: data.field,
            success: function (result) {
                if (result.code > 0) {
                    layer.msg(result.msg, {
                        time: 1000
                    });
                    $("input[name='id']").val(result.data);
                } else {
                    layer.alert(result.msg);
                }
            }
        });
        return false;
    });
    form.on('submit(gencode)', function (data) {
        data.field.queryColActJson = JSON.stringify(colActEditor.getData());
        data.field.queryColJson = JSON.stringify(colEditor.getData());
        data.field.queryActJson = JSON.stringify(actEditor.getData());
        data.field.queryConJson = JSON.stringify(condEditor.getData());
        data.field.formActJson = JSON.stringify(formActEditor.getData());
        data.field.formColJson = JSON.stringify(formColEditor.getData());
        data.field.viewColJson = JSON.stringify(viewColEditor.getData());
        $.ajax({
            url: "/page/gencode",
            dataType: "json",
            method: "POST",
            data: data.field,
            success: function (result) {
                if (result.code > 0) {
                    layer.msg(result.msg, {
                        time: 1000
                    });
                    $("input[name='id']").val(result.data);
                } else {
                    layer.alert(result.msg);
                }
            }
        });
        return false;
    });
});

//特殊UI

function selectPlusLoad(view, where, values) {
    layui.use(['selectPlus', 'jquery'], function () {
        var selectPlus = layui.selectPlus;
        // 单选
        selectPlus.render({
            el: view,
            type: "radio",
            valueName: "value",
            label: ["note"],
            url: "/dict/getDict",
            where: where,
            response: 'rows',
            values: values
        });
    });
}

function getSelectPlusWhere(code) {
    if (code == "field") {
        return {
            code: code,
            filter: $("select[name='entityId']").val()
        }
    } else {
        return {
            code: code
        }
    }
}

//编辑器框架=========================================

function ComponetEditor(view, viewTemplate, editTemplate,showLength) {

    this.$viewDom = $(view);
    var that = this;


    this.dataSave = function (data) {
        //提取JS的模板代码
        var $view = $("#editView");
        var newData = {};
        $.each($("input[name]", $view), function (index, dom) {
            //剔除selectPlus
            if ($(dom).attr("name").indexOf("selectPlus") < 0) {
                newData[$(dom).attr("name")] = $(dom).val();
            }
        });
        $.each($("select[name]", $view), function (index, dom) {
            //剔除selectPlus
            if ($(dom).attr("name").indexOf("selectPlus") < 0) {
                newData[$(dom).attr("name")] = $(dom).val();
            }
        });
        var $content;
        if (data == undefined) {
            //拷贝一份代码
            $content = $($(viewTemplate).html());
            that.$viewDom.children().last().before($content);
            $content.on("click", that.editBtn);
        } else {
            //提取原来DOM
            $content = that.$viewDom.children().eq(data._index);
        }
        $.each(newData, function (key, value) {
            //对拷贝代码赋值
            $(".layui-btn", $content).attr("data-"+key, value);
            //CSS控制
            if ("css" == key) {
                var $dom = $(".layui-btn", $content);
                $dom.removeClass();
                $dom.addClass("layui-btn " + value);
            }
            if ("width" == key && showLength) {
                $content.removeClass();
                $content.addClass("layui-col-md" + value);
            }
            if ("title" == key) {
                $("#title", $content).html(newData[key]);
            }

        });

    };


    this.addBtn = function () {
        showEdit(undefined, that.dataSave, undefined, $(editTemplate).html());
    };

    this.dataInit = function (data) {
        var $btnEditDom = $("#editView");
        $.each(data, function (name, value) {
            $("input[name='" + name + "']", $btnEditDom).val(value);
            $("select[name='" + name + "']", $btnEditDom)
                .find("option[value='"+value+"']")
                .attr("selected",true);
        });
    };

    this.editBtn = function () {
        var $btn = $(this).children().first();
        var data = $btn[0].dataset;
        data._index=$(this).index();
        showEdit(that.dataInit, that.dataSave, data, $(editTemplate).html())
    };
    this.getData = function () {
        var dataArrays = [];
        var doms = that.$viewDom.children();
        for (var i = 0; i < doms.length - 1; i++) {
            var data = $(doms[i]).children().first()[0].dataset;
            var newData = {};
            $.each(data,function(key,value){
               newData[key]=""+value;
            });
            dataArrays.push(newData);
        }
        return dataArrays;

    };

    var btns = this.$viewDom.children();
    for (var i = 0; i < btns.length; i++) {
        if (i == btns.length - 1) {
            $(btns[i]).on("click", that.addBtn.bind(btns[i]));
        } else {
            $(btns[i]).on("click", that.editBtn.bind(btns[i]));
        }

    }

}

//======================框架部分=========================
function showEdit(init, save, data, view) {
    var index = layer.open({
        type: 1,
        title: "详细信息",
        area: ["80%", "90%"],
        content: view,//这里content是一个普通的String
        btn: ['添加'],
        success: function (layero, index) {
            //1.渲染组件
            //加载selectPlus组件
            var selectPlusDom = $("div[selectPlus=true]", view);

            $.each(selectPlusDom, function (index, dom) {
                var code = $(dom).attr("selectPlus-code");
                var where = getSelectPlusWhere(code);
                var value = data ? data[$(dom).attr("name")] : "";
                selectPlusLoad("#editView div[name="+$(this).attr("name")+"]", where, [value]);
            });

            if (init != undefined) {
                init(data);
            }

            //2.渲染组件
            layui.use(['form'], function () {
                var form = layui.form;
                form.render();
            });

        },
        yes: function (index, layero) {
            if (save != undefined) {
                save(data);
            }
            layer.close(index)
        }
    });
}

function toLeft(obj) {
    var thisDom = $($(obj).parent(".layui-btn").parent());
    var preDom = thisDom.prev();
    if (preDom.length > 0) {
        thisDom.remove();
        preDom.before(thisDom);
    }
    stopPropagation();
}

function del(obj) {
    $(obj).parent().parent().remove();
    stopPropagation();
}


function toRight(obj) {
    var thisDom = $($(obj).parent(".layui-btn").parent());
    var nextDoms = thisDom.nextAll();
    if (nextDoms.length > 1) {
        thisDom.remove();
        $(nextDoms[0]).after(thisDom);
    }
    stopPropagation();
}
